package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.ShoppingCarDto;
import com.ruoyi.system.domain.dto.ShoppingDTO;
import com.ruoyi.system.domain.vo.OrderDetailsVo;
import com.ruoyi.system.domain.vo.ProductVo;
import com.ruoyi.system.mapper.AOrdersMapper;
import com.ruoyi.system.mapper.AProductMapper;
import com.ruoyi.system.mapper.ASetmealMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IACustomerService;
import com.ruoyi.system.service.IAOrdersService;
import com.ruoyi.system.service.IOrderDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 订单Service业务层处理
 *
 * @author 王家宁
 * @date 2024-09-02
 */
@Service
@Slf4j
public class AOrdersServiceImpl extends ServiceImpl<AOrdersMapper, AOrders> implements IAOrdersService {
    @Autowired
    private IOrderDetailsService orderDetailsService;

    @Autowired
    private AOrdersMapper aOrdersMapper;

    @Autowired
    private AProductMapper productMapper;

    @Autowired
    private ASetmealMapper setmealMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IACustomerService customerService;

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public AOrders selectAOrdersById(Long id) {
        return aOrdersMapper.selectAOrdersById(id);
    }

    /**
     * 查询订单列表
     *
     * @param aOrders 订单
     * @return 订单
     */
    @Override
    public List<OrdersVo> selectAOrdersList(AOrders aOrders) {
        List<OrdersVo> ordersVos = new ArrayList<>();
        List<AOrders> aOrders2 = aOrdersMapper.selectAOrdersList(aOrders);
        aOrders2.forEach(aOrders1 -> {
            OrdersVo ordersVo = new OrdersVo();
            ordersVo.setId(aOrders1.getId());
            ordersVo.setOrderAmount(aOrders1.getOrderAmount());
            ordersVo.setOrderCustomer(sysUserMapper.selectUserById(aOrders1.getOrderCustomer()).getUserName());
            ordersVos.add(ordersVo);
        });
        return ordersVos;
    }

    /**
     * 我的订单
     * @return
     */
    @Override
    public List<OrdersVo> selectMyOrders(){
        List<OrdersVo> ordersVos = new ArrayList<>();
        AOrders aOrders = new AOrders();
        SysUser sysUser = ShiroUtils.getSysUser();
        Long userId = sysUser.getUserId();
        aOrders.setOrderCustomer(userId);
        List<AOrders> aOrders2 = aOrdersMapper.selectAOrdersList(aOrders);
        aOrders2.forEach(aOrders1 -> {
            OrdersVo ordersVo = new OrdersVo();
            ordersVo.setId(aOrders1.getId());
            ordersVo.setOrderAmount(aOrders1.getOrderAmount());
            ordersVo.setOrderCustomer(sysUserMapper.selectUserById(aOrders1.getOrderCustomer()).getUserName());
            ordersVos.add(ordersVo);
        });
        return ordersVos;
    }

    /**
     * 新增订单
     *
     * @param aOrders 订单
     * @return 结果
     */
    @Override
    public int insertAOrders(AOrders aOrders) {
        aOrders.setCreateTime(DateUtils.getNowDate());
        aOrders.setUpdateTime(DateUtils.getNowDate());

        return aOrdersMapper.insertAOrders(aOrders);
    }

    @Override
    public int saveOrdersAndDetails(ShoppingCarDto shoppingCarDto) {
        SysUser sysUser = ShiroUtils.getSysUser();
        Long userId = sysUser.getUserId();
        List<ShoppingDTO> shoppingDTOList = shoppingCarDto.getShoppingDTOList();

        AOrders aOrders = new AOrders();
        aOrders.setOrderAmount(0.0);
        aOrders.setOrderCustomer(userId);
        aOrders.setCreateTime(DateUtils.getNowDate());
        aOrders.setUpdateTime(DateUtils.getNowDate());
        this.insertAOrders(aOrders);
        double amount = 0;
        long score = 0L;
        for (ShoppingDTO shoppingDTO : shoppingDTOList) {
            Integer proType = shoppingDTO.getProType();
            String id = shoppingDTO.getId().split("_")[0];
            Integer quantity = shoppingDTO.getQuantity();
            OrderDetails orderDetails = new OrderDetails();
//            甜品
            if (proType == 0) {
                AProduct product = productMapper.selectAProductById(Long.valueOf(id));
                amount = amount + quantity * product.getProductPrice();
                orderDetails.setProductId(product.getId());
                product.setProductStock(product.getProductStock() - quantity);
                productMapper.updateAProduct(product);
                score = score + product.getProductScore();

            } else {
//            套餐
                ASetmeal setmeal = setmealMapper.selectASetmealById(Long.valueOf(id));
                amount = amount + quantity * setmeal.getSetmealPrice();
                orderDetails.setSetmealId(setmeal.getId());
                score = score + setmeal.getSocre();
            }

//            插入订单详情信息
            orderDetails.setOrderId(aOrders.getId());
            orderDetails.setQuantity(quantity);
            orderDetails.setCreateTime(DateUtils.getNowDate());
            orderDetails.setUpdateTime(DateUtils.getNowDate());
            orderDetailsService.insertOrderDetails(orderDetails);
//            查询当前用户是否为会员
            ACustomer customer = new ACustomer();
            customer.setUserId(ShiroUtils.getUserId());
            List<ACustomer> aCustomers = customerService.selectACustomerList(customer);
//            如果是本店会员，记录当前购买积分
            if (!CollectionUtils.isEmpty(aCustomers)){
                ACustomer customer1 = aCustomers.get(0);
                customer1.setSocre(score);
                customerService.updateACustomer(customer1);
            }

        }
        aOrders.setOrderAmount(amount);
        this.updateAOrders(aOrders);
        return 1;
    }

    /**
     * 修改订单
     *
     * @param aOrders 订单
     * @return 结果
     */
    @Override
    public int updateAOrders(AOrders aOrders) {
        return aOrdersMapper.updateAOrders(aOrders);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteAOrdersByIds(String ids) {
        return aOrdersMapper.deleteAOrdersByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    public int deleteAOrdersById(Long id) {
        return aOrdersMapper.deleteAOrdersById(id);
    }

    /**
     * 根据订单id查询订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderDetailsVo getOrderDetails(Long id) {
        List<OrderDetails> orderDetails = orderDetailsService.selectOrderDetailListByOrderId(id);
        if (Objects.isNull(orderDetails)) {
            log.info("查询订单详情为空");
            return null;
        }
        List<ProductVo> productVoList = new ArrayList<>();
        double amount = 0.0;
        int socre = 0;
        if (CollectionUtils.isEmpty(orderDetails)) {
            log.info("根据订单id:{}获取订单详情集合为空", id);
            return null;
        }
        AtomicReference<Date> createTime = new AtomicReference<>(new Date());
        for (OrderDetails od :
                orderDetails) {
            createTime.set(od.getCreateTime());
            Long productId = od.getProductId();
            Long setMealId = od.getSetmealId();
            Integer quantity = od.getQuantity();
            AProduct aProduct = productMapper.getProductById(productId);
            ASetmeal setmeal = setmealMapper.getSetMealById(setMealId);
            ProductVo productVo = null;
            if (Objects.nonNull(aProduct)) {
                amount = amount + aProduct.getProductPrice();
                socre = socre + aProduct.getProductScore().intValue();
                productVo = new ProductVo(aProduct.getProductName(), aProduct.getProductPrice(), quantity);
            }
            if (Objects.nonNull(setmeal)) {
                amount = amount + setmeal.getSetmealPrice();
                socre = socre + setmeal.getSetmealPrice().intValue();
                productVo = new ProductVo(setmeal.getSetmealName(), setmeal.getSetmealPrice().doubleValue(), quantity);
            }
            productVoList.add(productVo);
        }
        OrderDetailsVo orderDetailsVo = new OrderDetailsVo();
        orderDetailsVo.setSocre(socre);
        orderDetailsVo.setAmount(amount);
        orderDetailsVo.setProductVoList(productVoList);
        orderDetailsVo.setPayDateTime(createTime.get());
        return orderDetailsVo;
    }
}
